package cz.tomasdvorak.cars.pages.vehicle;

import cz.tomasdvorak.cars.auth.Auth;
import cz.tomasdvorak.cars.dto.User;
import cz.tomasdvorak.cars.dto.Vehicle;
import cz.tomasdvorak.cars.dto.VehicleBodyType;
import cz.tomasdvorak.cars.pages.BasePage;
import cz.tomasdvorak.cars.utils.Lists;
import cz.tomasdvorak.cars.wicket.components.ExternalImageUrl;
import cz.tomasdvorak.cars.wicket.components.breadcrumbs.BreadcrumbItem;
import cz.tomasdvorak.cars.wicket.components.model.NoneFileUploadModel;
import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.link.ExternalLink;
import org.apache.wicket.model.*;
import org.apache.wicket.util.lang.Bytes;
import org.apache.wicket.validation.validator.MinimumValidator;
import org.apache.wicket.validation.validator.MaximumValidator;

import java.util.List;

@AuthorizeInstantiation(Auth.USER)
public class VehicleEditingPage extends BasePage {

    private final class VehicleForm extends Form<Vehicle> {

        private User owner;
        private FileUploadField upload;

        public VehicleForm(String id, IModel<Vehicle> vehicleModel) {
            super(id, vehicleModel);
            setMultiPart(true);
            setMaxSize(Bytes.megabytes(1));
            if (vehicleModel.getObject().getOwnerId() > -1) {
                this.owner = VehicleEditingPage.this.getUserDao().getUserById(
                        vehicleModel.getObject().getOwnerId());
            }
            add(new FeedbackPanel("feedback"));
            add(new TextField<String>("manufacturer").setRequired(true));
            add(new TextField<String>("model").setRequired(true));
            add(new TextField<Integer>("price").setRequired(true).add(new MinimumValidator<Integer>(1)).add(new MaximumValidator<Integer>(100000000)));
            add(new TextField<Integer>("gasCapacity").setRequired(true).add(new MinimumValidator<Integer>(1)).add(new MaximumValidator<Integer>(1000)));
            add(new DropDownChoice<VehicleBodyType>("type", Lists.arrayList(
                    VehicleBodyType.values()), new IChoiceRenderer<VehicleBodyType>() {
                public Object getDisplayValue(VehicleBodyType object) {
                    return getLocalizer().getString("vehicleBodyType." + object.name(),
                            VehicleEditingPage.this);
                }

                public String getIdValue(VehicleBodyType object, int index) {
                    return "" + index;
                }
            }));
            add(new TextField<String>("registrationNumber").setRequired(true));
            add(new DropDownChoice<User>("owner", new PropertyModel<User>(this, "owner"),
                    getAllUsers(), new IChoiceRenderer<User>() {
                        public Object getDisplayValue(User object) {
                            return object.getName();
                        }

                        public String getIdValue(User object, int index) {
                            return "" + index;
                        }
                    }).setNullValid(false));
            upload = new FileUploadField("imageUpload", new NoneFileUploadModel());
            add(upload);
            add(new ExternalLink("thumbLink", vehicleModel.getObject().getImageUrl()).add(new ExternalImageUrl("image", vehicleModel.getObject().getImageThumbUrl())));
        }

        private List<? extends User> getAllUsers() {
            return VehicleEditingPage.this.getUserDao().getAllUSers();
        }

        @Override
        protected void onSubmit() {
            try {
                Vehicle vehicle = getModelObject();
                vehicle.setOwnerId(owner.getId());
                VehicleEditingPage.this.getVehiclesDao().insertOrUpdate(vehicle);
                if (this.upload.getFileUpload() != null) {
                    VehicleEditingPage.this.getVehiclesDao().appendImage(vehicle,
                            this.upload.getFileUpload());
                }
                setResponsePage(AllVehiclesPage.class);
            } catch (Exception e) {
                error(e);
            }
        }
    }

    public VehicleEditingPage() {
        this(null);
    }

    public VehicleEditingPage(IModel<Vehicle> model) {
        if(model == null) {
            model = new Model<Vehicle>(getVehiclesDao().createNewDto());
        }
        add(new VehicleForm("vehicleForm", new CompoundPropertyModel<Vehicle>(model)));
    }

    protected List<BreadcrumbItem> getPageBreadcrumb() throws Exception {
        return Lists.arrayList(new BreadcrumbItem(new ResourceModel("breadcrumb.knownVehicles"), AllVehiclesPage.class), new BreadcrumbItem(new ResourceModel("breadcrumb.editingVehicle")));
    }
}
